package mousecollide;

import java.awt.Color;
import java.awt.Graphics;


/**
 * Super class of all Sprites.<br>
 * Have ability to detect collision with other sprite,<br>
 * Round is the preset shape of its sub classes.
 * 
 * @author nbxx
 *
 */
public abstract class Sprite
{
	protected int speed, radius;
	protected Vector velocity, unit, position;

	protected int frameX, frameY;
	protected boolean isMoving;
	protected Color color;
	
	/*Coefficient of restitution*/
	private final double COR = 0.8f;
	
	protected Sprite(int r ,int v)
	{
		radius = r;
		speed = v;
		color = Color.DARK_GRAY;
		velocity = new Vector();
		position = new Vector();
	}
	
	public void setPosition(int x, int y)
	{
		position.x = x;
		position.y = y;
	}
	
	public void setFrame(int x, int y)
	{
		frameX = x;
		frameY = y;
	}
	
	public void move()
	{
			if (!(position.x + velocity.x + radius < frameX && position.x + velocity.x > radius))
				velocity.x = -velocity.x;
			if (!(position.y + velocity.y + radius < frameY && position.y + velocity.y > radius))
				velocity.y = -velocity.y;
			position.add(velocity);
	}
	
	public boolean collideWith(Sprite s)
	{
		if (Vector.subtraction(position, s.position).length() < s.radius + radius)
		{
			return true;
		}
		return false;
	}
	
	/**
	 * Return the direction vector after collision.<br>
	 * Performance need improvement.
	 * 
	 * @param s Target Sprite
	 * @return Direction Vector
	 */
	public void bounce(Sprite s)
	{
		velocity.sub(Vector.subtraction(s.position, position).mul(s.speed).div(radius+s.radius));
		velocity.mul(COR);
	}

	public void setDestination(int x, int y)
	{
		isMoving = true;
		
		velocity.x = x - position.x;
		velocity.y = y - position.y;
		if (!velocity.isZero())
		{
			velocity.normalize();
			velocity.mul(speed);
		}
	}

	public void draw(Graphics g)
	{
		g.setColor(color);
		g.fillOval((int)position.x - radius, (int)position.y - radius, radius<<1, radius<<1);
	}
}
